﻿#region Header
//************************************************************************************
// Name: BasePage
// Description:BasePage contains common Methods
// Created On:  02-Aug-2011
// Created By:  Swathi
// Last Modified On:
// Last Modified By:
// Last Modified Reason:
//*************************************************************************************
#endregion Header
using System;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;

using Base.Utils;
using Base.Utils.Logging;
using Base.Utils.Factory;

public abstract class BasePage : Page
{
    #region Fields

    #endregion Fields

    #region Properties

    /// <summary>
    /// 
    /// </summary>
    public static ILogger Logger
    {
        get
        {
            return UtilsFactory.Logger;
        }
    }

    public static Uri AbsoluteWebRoot
    {
        get
        {
            var context = HttpContext.Current;
            if (context == null)
                throw new System.Net.WebException("The current HttpContext is null");
            return new Uri(context.Request.Url.Scheme + "://" + context.Request.Url.Authority + RelativeWebRoot);
        }
    }

    public static string RelativeWebRoot
    {
        get { return VirtualPathUtility.ToAbsolute("~/"); }
    }
    #endregion Properties

    #region Methods

    /// <summary>
    /// 
    /// </summary>
    /// <param name="fileNameWithJsFolderName"></param>
    public virtual void AddExternalJavaScript(string fileNameWithJsFolderName)
    {
        var script = new HtmlGenericControl("script");
        script.Attributes["type"] = "text/javascript";
        script.Attributes["src"] = AbsoluteWebRoot + fileNameWithJsFolderName + "?ver=" + ConfigurationManager.AppSettings["JSVersion"];
        //script.Attributes["charset"] = "ISO-8859-1";
        //script.Attributes["defer"] = "defer";
        Page.Header.Controls.Add(script);       
    }

    public virtual void AddScriptBlockFromExternalFileInTheEnd(string fileNameWithJsFolderName)
    {
        string uri = AbsoluteWebRoot + fileNameWithJsFolderName;
        string scriptBlock = "<script language=JavaScript>" + CommonUtils.GetResourceAsString(uri) + "</script>";
        Page.RegisterStartupScript(uri, scriptBlock);      
    }

    /// <summary>
    /// Adds the generic link to the header.
    /// </summary>
    public virtual void AddGenericLink(string relation, string title, string href)
    {
        var link = new HtmlLink();
        link.Attributes["rel"] = relation;
        link.Attributes["title"] = title;
        link.Attributes["href"] = href;
        Page.Header.Controls.Add(link);
    }

    /// <summary>
    /// Adds the generic link to the header.
    /// </summary>
    public virtual void AddGenericLink(string type, string relation, string title, string href)
    {
        var link = new HtmlLink();
        link.Attributes["type"] = type;
        link.Attributes["rel"] = relation;
        link.Attributes["title"] = title;
        link.Attributes["href"] = href;
        Page.Header.Controls.Add(link);
    }

    public virtual void AddInlineAjaxCode(Control control, Type type, string jsScript)
    {
        ScriptManager.RegisterStartupScript(control, type, "AjaxScript_" + CommonUtils.GetRandom(5), jsScript, true);
    }

    public virtual void AddInlineJavascriptCodes(Type objectType, string jsScript)
    {
        ClientScript.RegisterStartupScript(objectType, "script_" + CommonUtils.GetRandom(5), jsScript, true);
    }

    /// <summary>
    /// Add a meta tag to the page's header.
    /// </summary>
    public virtual void AddMetaTag(string name, string value)
    {
        if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(value))
            return;

        var meta = new HtmlMeta { Name = name, Content = value };
        Page.Header.Controls.Add(meta);
    }

    /// <summary>
    /// Converts the simple string to JSON string.
    /// This function is mainly used to parse the system generated exception messages
    /// where carriage return, line feed, single quotes will cause the Javascript function to crack
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    /// <remarks></remarks>
    public string ConvertStringToJsonString(string input)
    {
        return (input != null) ? new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(input) : "";
    }

    public int GetProfileId(string loginInfo)
    {
        var loginInfoAr = loginInfo.Split(',');
        return CommonUtils.StrToInt(loginInfoAr[0]);
    }
    protected virtual void AddEmbeddedJavaScript(string name)
    {
        var script = new HtmlGenericControl("script");
        script.Attributes["type"] = "text/javascript";
        script.Attributes["src"] = Page.ClientScript.GetWebResourceUrl(typeof(BasePage), name);
        Page.Header.Controls.Add(script);
    }

    protected virtual void AddExternalCss(string fileNameWithCssFolderName)
    {
        var css = new HtmlGenericControl("link");
        css.Attributes["rel"] = "stylesheet";
        css.Attributes["type"] = "text/css";
        css.Attributes["href"] = AbsoluteWebRoot + fileNameWithCssFolderName;
        Page.Header.Controls.Add(css);
    }

    protected override void OnLoad(EventArgs e)
    {

        //TODO: This needs to be removed after the prototype phase
        //Added localhost check since, below redirect will not work in test or production environment
        var context = HttpContext.Current;
        if (context == null)
            throw new System.Net.WebException("The current HttpContext is null");
        if (((context.Request.Url.Authority.ToLower()).Contains("localhost")))
        {
            if (Request.QueryString.Count > 0)
            {
                Response.Redirect(AbsoluteWebRoot + Request.Url.AbsolutePath.Substring(1, Request.Url.AbsolutePath.Length - 1), true);
            }
        }

        var loginName = string.Empty;
        var isLoggedIn = false;

        AddExternalJavaScript("js/YUI/utilities/utilities.js");
        AddExternalJavaScript("js/YUI/yahoo-dom-event/yahoo-dom-event.js");
        AddExternalJavaScript("js/YUI/container/container-min.js");
        AddExternalJavaScript("js/YUI/element/element-min.js");
        AddExternalJavaScript("js/YUI/json/json-min.js");
        AddExternalJavaScript("js/Jquery/jquery.js");
        AddExternalJavaScript("js/Jquery/jquery.ui.core.js");
        AddExternalJavaScript("js/Jquery/jquery.ui.widget.js");
        AddExternalJavaScript("js/Jquery/jquery.ui.mouse.js");
        AddExternalJavaScript("js/Jquery/jquery.ui.position.js");
        AddExternalJavaScript("js/Jquery/jquery.ui.dialog.js");
        AddExternalJavaScript("js/Jquery/jquery.ui.draggable.js");
        AddExternalJavaScript("js/Jquery/jquery.ui.datepicker.js");
        //AddExternalJavaScript("js/Jquery/jquery.ui.button.js");      
        AddExternalJavaScript("js/Jquery/jquery.cookie.js");
        AddExternalJavaScript("js/Jquery/jquery.tipsy.js");
        AddExternalJavaScript("js/Jquery/jquery.tmpl.js");
        AddExternalJavaScript("js/Jquery/json2.js");
        AddExternalJavaScript("js/left-menu.js");
        AddExternalJavaScript("js/YUIHelperByVMO/DatatableHelper.js");
        AddExternalJavaScript("js/Chinook.Web.Utils.js");
        AddExternalJavaScript("js/Jquery/jquery.validate.js");//Added for validation
        AddExternalJavaScript("js/Jquery/custom.validation.js");//Added for validation
        AddExternalJavaScript("js/Jquery/jquery.vm-plugins.js");
      

        AddInlineJavascriptCodes(GetType(), "_absWebRoot='" + AbsoluteWebRoot + "';");
        //var role = string.Empty;
        //if (Context.User.Identity.IsAuthenticated)
        //{
        //    isLoggedIn = true;
        //    var nameAr = Context.User.Identity.Name.Split('*');
        //    loginName = nameAr[0];
        //    role = nameAr[1];// Please donot comment this line -- Swathi
        //}
        //AddInlineJavascriptCodes(GetType(), "var _isLoggedIn='" + isLoggedIn.ToString() + "';var _loginName='" + loginName + "';");
        //AddInlineJavascriptCodes(GetType(), "var _userRole='" + role + "';");


        if (!Page.IsPostBack)
        {

        }
        base.OnLoad(e);
    }

    #endregion Methods

    #region Other

    //============================================================
    //    Page Events
    //============================================================

    #endregion Other
}